package com.ljz.controller;

import com.github.pagehelper.Page;
import com.ljz.entity.Result;
import com.ljz.entity.User;
import com.ljz.service.impl.DeptServiceImpl;
import com.ljz.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private DeptServiceImpl deptService;

    @RequestMapping("/toList")
    public ModelAndView toList(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("list");
        return mv;
    }
    @RequestMapping("/getUsersByPage")
    public Map getUsersByPage(String name, Integer currentPage, Integer pageSize) {
        Page<User> users = userService.findAll(name, currentPage, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("users", users);
        map.put("total", users.getTotal());
        map.put("pages", users.getPages());
        map.put("currentPage", currentPage);
        map.put("pageSize", pageSize);
        return map;
    }
    @RequestMapping("/addUser")
    public Result insert(@RequestBody User user) {
        userService.save(user);
        return new Result();
    }

    @RequestMapping("/editUser")
    public ModelAndView edit(int id) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("user",userService.findById(id));
        mv.addObject("depts", deptService.findAll());
        mv.setViewName("edit");
        return mv;
    }
    @RequestMapping("/updateUser")
    public Result update(@RequestBody User user) {
        userService.update(user);
        return new Result();
    }
    @RequestMapping("/deleteUser")
    public ModelAndView delete(int id) {
        userService.delete(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject(new Result());
        mv.setViewName("list");
        return mv;
    }
    @RequestMapping("/getDepts")
    public List getDepts() {
        return deptService.findAll();
    }

}
